<template>
  <div class="btn_warp" style="height:32px;width: 100%;padding-top: 5px;padding-bottom: 10px">
    <el-button type="success" plain class="btn_add" style="width:100px" @click="onAddItem">添加</el-button>
    <el-button type="danger" plain class="btn_delete" style="width: 100px" @click="onDeleteItem">删除</el-button>
    <el-button type="success" style="float: right;margin-right: 30px" @click.prevent="handleSearch">查询</el-button>
    <el-button type="success" style="float: right;margin-right: 5px" @click.prevent="handleClean">全部清空</el-button>
    <el-input v-model="search3" clearable placeholder="按解决情况查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search2" clearable placeholder="按投诉日期查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search1" clearable placeholder="按投诉对象查询" style="float: right;width: 250px;margin-right: 15px"/>
  </div>
  <el-table @selection-change="handleSelsChange" :data="filterTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe border style="width: 100%;" max-height="472" height="472" :cell-style="{ textAlign: 'center' }">
    <el-table-column type="selection" width="40" >
    </el-table-column>
    <el-table-column fixed prop="" label="序号" width="60" :show-overflow-tooltip="true">
      <template #default="scope">
        {{scope.$index+1}}
      </template>
    </el-table-column>
    <el-table-column fixed prop="complainProblem" label="投诉问题" width="200" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.complainProblem" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.complainProblem }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyAddress1" label="投诉对象" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.propertyAddress1" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.propertyAddress1 }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="complainDate" label="投诉日期" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-date-picker value-format="YYYY-MM-DD" size="small" style="width: 120px ;" v-model="scope.row.complainDate" type="date" placeholder="选择一个日期"></el-date-picker>
            </span>
        <span v-else>{{ scope.row.complainDate }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyAddress2" label="创建用户" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
        <span>{{ scope.row.propertyAddress2 }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="complainPhone" label="联系电话" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.complainPhone" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.complainPhone }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="complainSituation" label="解决情况" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-select v-model="scope.row.complainSituation" placeholder="选择" size="small">
                <el-option v-for="item in situationOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </span>
        <span v-else>{{ scope.row.complainSituation }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="complainSolvedate" label="处理日期" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-date-picker value-format="YYYY-MM-DD" size="small" style="width: 120px ;" v-model="scope.row.complainSolvedate" type="date" placeholder="选择一个日期"></el-date-picker>
            </span>
        <span v-else>{{ scope.row.complainSolvedate }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="complainSolvename" label="处理人员" width="175" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.complainSolvename" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.complainSolvename }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="265" :show-overflow-tooltip="true">
      <template #default="scope">
        <el-button type="warning" round size="small" @click.prevent="updateRow(scope.$index)">修改</el-button>
        <el-button type="primary" round size="small" @click.prevent="saveRow(scope.$index,scope.row.complainId)">保存</el-button>
        <el-button type="danger" round size="small" @click.prevent="deleteRow(scope.$index,scope.row.complainId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page_warp">
    <el-pagination  background @current-change="handleCurrentChange" v-model:page-size="pageSize" v-model:current-page="currentPage" layout="prev, pager, next , jumper" :total="filterTableData.length"></el-pagination>
  </div>
</template>

<script>
import { ElMessage,ElMessageBox } from 'element-plus'
import { ref,onMounted } from 'vue'
import {nanoid} from 'nanoid'
import axios from "axios";
import {useRouter} from 'vue-router'

export default {
  name: "HouseHold",
  setup(){
    const tableSels=ref([])
    const tableData = ref([])
    const pageSize=ref(10)
    const currentPage=ref(1)
    const router=useRouter()
    const situationOptions=[
      {
        value:'未解决',
        label:'未解决'
      },
      {
        value:'处理中',
        label:'处理中'
      },
      {
        value:'已解决',
        label:'已解决'
      }
    ]
    const search1=ref('')
    const search2=ref('')
    const search3=ref('')
    //条件过滤
    let filterTableData =ref([])

    //按条件进行查询
    function handleSearch(){
      filterTableData.value=tableData.value.filter(
          (data) => data.propertyAddress1.toLowerCase().includes(search1.value.toLowerCase()) //匹配投诉对象
              && data.complainDate.toLowerCase().includes(search2.value.toLowerCase()) //匹配投诉日期
              && data.complainSituation.toLowerCase().includes(search3.value.toLowerCase()) //匹配解决情况
      )
    }
    //清空查询条件
    function handleClean(){
      search1.value=''
      search2.value=''
      search3.value=''
    }
    //选择添加事件
    function onAddItem(){
      tableData.value.push({
        complainId:nanoid(),   //投诉id
        complainProblem: '',  //投诉问题
        complainPhone: '',  //联系电话
        complainForeignkey1:'',   //房产id(投诉对象)
        complainForeignkey2:'',    //房产id(创建人)
        complainDate: formatDate(new Date()),  //投诉日期
        complainSituation: '未解决',  //解决情况
        complainSolvedate: '',  //处理日期
        complainSolvename: '',  //处理人员
        propertyAddress1: '',  //投诉对象
        propertyAddress2: JSON.parse(sessionStorage.getItem("user")).username,  //创建人,  //创建用户
        isUpdate:true,    //是否为编辑状态
        isAdd:true,    //是否为新增状态
      })
      currentPage.value=Math.ceil(tableData.value.length/pageSize.value)
    }
    //选择删除事件
    function onDeleteItem(){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableSels.value.forEach((tableSel)=>{
          tableData.value.forEach((item,index)=>{
            if(item===tableSel){
              tableData.value.splice(index,1)
              //发送请求进行数据删除
              axios.get('http://localhost:8085/deleteComplain',{
                params:{
                  complainId:item.complainId,   //住户id
                }
              }).then(
                  ()=>{
                    ElMessage({type:'success',message:'删除成功！'})
                  },
                  ()=>{
                    ElMessage({type:'error',message:'删除失败！'})
                    setTimeout(()=>{
                      router.go(0)
                    },500)
                  }
              )
            }
          })
        })
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //行修改事件
    function updateRow(index) {
      filterTableData.value[pageSize.value * (currentPage.value - 1) + index].isUpdate = true
    }
    //行保存事件
    function saveRow(index){
      let complainObj=filterTableData.value[pageSize.value*(currentPage.value-1)+index]
      if(!complainObj.isUpdate){
        ElMessage({message:'没有数据需要保存！'})
      }else if(complainObj.complainProblem === ''){  //判断姓名与物业地址是否为空
        ElMessage({message:'投诉问题不能为空！'})
      }else if(complainObj.propertyAddress1 === ''){
        ElMessage({message:'投诉对象不能为空！'})
      }else if(complainObj.complainDate === ''){
        ElMessage({message:'投诉日期不能为空！'})
      }else if(complainObj.propertyAddress2 === ''){
        ElMessage({message:'创建用户不能为空！'})
      }else if(complainObj.propertyAddress1 == complainObj.propertyAddress2){
        ElMessage({message:'投诉对象不能与创建用户一样！'})
      } else if(complainObj.isAdd){
        if(isRepeat(complainObj,index)) return
        //1.发送请求判断投诉对象及创建用户是否存在
        axios.get('http://localhost:8085/hasPropertyAddresss',{
          params:{
            propertyAddress1:complainObj.propertyAddress1,   //投诉对象
            propertyAddress2:complainObj.propertyAddress2 //创建用户
          }
        }).then(
            (resp)=>{
              if(resp.data===0){
                ElMessage({type: 'error',message:'保存失败，投诉对象和创建用户不存在！'})
              }else if(resp.data===1){
                ElMessage({type: 'error',message:'保存失败，投诉对象不存在且创建用户所在物业并未售出！'})
              }else if(resp.data===2){
                ElMessage({type: 'error',message:'保存失败，创建用户不存在！'})
              }else if(resp.data===3){
                ElMessage({type: 'error',message:'保存失败，创建用户所在物业并未售出！'})
              }else if(resp.data===5){
                ElMessage({type: 'error',message:'保存失败，投诉对象不存在！'})
              } else if(resp.data===4){
                axios.get('http://localhost:8085/addComplain',{
                  params:{
                    complainId:complainObj.complainId,   //投诉id
                    complainProblem:complainObj.complainProblem,  //投诉问题
                    complainPhone:complainObj.complainPhone,  //联系电话
                    complainForeignkey1:complainObj.complainForeignkey1,   //房产id(投诉对象)
                    complainForeignkey2:complainObj.complainForeignkey2,   //房产id(创建人)
                    complainDate:complainObj.complainDate,   //投诉日期
                    complainSituation:complainObj.complainSituation,  //解决情况
                    complainSolvedate:complainObj.complainSolvedate,  //处理日期
                    complainSolvename:complainObj.complainSolvename,  //处理人员
                    propertyAddress1:complainObj.propertyAddress1,  //投诉对象
                    propertyAddress2:complainObj.propertyAddress2,  //创建用户
                  }
                }).then(
                    ()=>{
                      ElMessage({type:'success',message:'保存成功！'})
                      //4.关闭输入框
                      complainObj.isUpdate=false
                      complainObj.isAdd=false
                    },
                    ()=>{
                      ElMessage({type:'error',message:'保存失败！'})
                    }
                )
              }
            },
            ()=>{
              ElMessage({type: 'error',message:'网络请求失败！'})
            }
        )
      }else {
        if(isRepeat(complainObj,index)) return
        //1.发送请求判断投诉对象及创建用户是否存在
        axios.get('http://localhost:8085/hasPropertyAddresss',{
          params:{
            propertyAddress1:complainObj.propertyAddress1,   //投诉对象
            propertyAddress2:complainObj.propertyAddress2 //创建用户
          }
        }).then(
            (resp)=>{
              if(resp.data===0){
                ElMessage({type: 'error',message:'保存失败，投诉对象和创建用户不存在！'})
              }else if(resp.data===1){
                ElMessage({type: 'error',message:'保存失败，投诉对象不存在！'})
              }else if(resp.data===2){
                ElMessage({type: 'error',message:'保存失败，创建用户不存在！'})
              }else if(resp.data===3){
                ElMessage({type: 'error',message:'保存失败，创建用户所在物业并未售出！'})
              } else if(resp.data===4) {
                axios.get('http://localhost:8085/updateComplain',{
                  params:{
                    complainId:complainObj.complainId,   //投诉id
                    complainProblem:complainObj.complainProblem,  //投诉问题
                    complainPhone:complainObj.complainPhone,  //联系电话
                    complainForeignkey1:complainObj.complainForeignkey1,   //房产id(投诉对象)
                    complainForeignkey2:complainObj.complainForeignkey2,   //房产id(创建人)
                    complainDate:complainObj.complainDate,   //投诉日期
                    complainSituation:complainObj.complainSituation,  //解决情况
                    complainSolvedate:complainObj.complainSolvedate,  //处理日期
                    complainSolvename:complainObj.complainSolvename,  //处理人员
                    propertyAddress1:complainObj.propertyAddress1,  //投诉对象
                    propertyAddress2:complainObj.propertyAddress2,  //创建用户
                  }
                }).then(
                    ()=>{
                      ElMessage({type:'success',message:'保存成功！'})
                      //4.关闭输入框
                      complainObj.isUpdate=false
                      complainObj.isAdd=false
                    },
                    ()=>{
                      ElMessage({type:'error',message:'保存失败！'})
                    }
                )
              }
            },
            ()=>{
              ElMessage({type: 'error',message:'网络请求失败！'})
            }
        )
      }
    }
    //行删除事件
    function deleteRow(index,complainId){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        axios.get('http://localhost:8085/deleteComplain',{
          params:{
            complainId:complainId,   //投诉id
          }
        }).then(
            ()=>{
              ElMessage({type:'success',message:'删除成功！'})
              tableData.value.splice(pageSize.value*(currentPage.value-1)+index,1)
            },
            ()=>{
              ElMessage({type:'error',message:'删除失败！'})
            }
        )
      }).catch(() => {
        ElMessage({type: 'info', message: '保存失败！',})
      })
    }
    //分页事件
    function handleCurrentChange(value){
      currentPage.value = value;
    }
    //处理多选
    const handleSelsChange=(sels)=>{
      tableSels.value=sels
    }

    //挂载加载数据
    onMounted(()=>{
      axios.get('http://localhost:8085/getComplainByAddress',{
        params:{
          address:JSON.parse(sessionStorage.getItem("user")).username
        }
      }).then(
          (response)=>{
            tableData.value=response.data
            filterTableData.value=response.data
          },
          ()=>{
          }
      )
    })

    //格式化Date类型
    function formatDate(val) {
      if(isNaN(val)) return ''
      const date = new Date(Number(val)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + "-";
      const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
      const D = date.getDate() + " ";
      // const h = date.getHours() + ":";
      // const m = date.getMinutes() + ":";
      // const s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());
      return Y + M + D;
    }
    //判断记录是否重复
    function isRepeat(Obj,index){
      let tip=0
      tableData.value.forEach((item,indexx)=>{
        if(Obj.complainProblem==item.complainProblem  && Obj.propertyAddress1==item.propertyAddress1  && formatDate(Date.parse(Obj.complainDate))==formatDate(Date.parse(item.complainDate))  && Obj.propertyAddress2==item.propertyAddress2  && (pageSize.value*(currentPage.value-1)+index)!=indexx){
          tip=1
        }
      })
      if(tip==1){
        ElMessage({type:'error',message:'保存失败,该投诉信息记录已存在！'})
        return true
      }else {
        return false
      }
    }

    return{
      tableSels,
      tableData,
      filterTableData,
      search1,
      search2,
      search3,
      pageSize,
      currentPage,
      formatDate,
      onAddItem,
      onDeleteItem,
      updateRow,
      saveRow,
      deleteRow,
      handleCurrentChange,
      handleSelsChange,
      situationOptions,
      isRepeat,
      handleSearch,
      handleClean
    }
  }
}
</script>

<style scoped>
.el-table{
  /*padding: 20px 20px 20px 20px;*/
}
.page_warp{
  width: 600px;
  margin: 5px auto;
  height: 40px;
}
.el-pagination{
  margin-right: 50px;
}
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color-base);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>